package com.heima.kafka.stream;

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KeyValueMapper;
import org.apache.kafka.streams.kstream.TimeWindows;
import org.apache.kafka.streams.kstream.ValueMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

@Configuration
@Slf4j
public class KafkaStreamHelloListener {


    @Bean
    public KStream<String, String> kStream(StreamsBuilder streamsBuilder) {

        //创建KStream对象，同时从指定哪个topic中接收消息
        KStream<String, String> stream = streamsBuilder.stream("itcast-topic-input");

        /**
         * 处理消息的value值
         */
        stream
                .flatMapValues(new ValueMapper<String, Iterable<String>>() {
                    @Override
                    public Iterable<String> apply(String value) {
                        return Arrays.asList(value.split(" "));
                    }
                })
                //按照value进行聚合处理
                .groupBy(new KeyValueMapper<String, String, Object>() {
                    @Override
                    public Object apply(String key, String value) {
                        return value;
                    }
                })
                //时间窗口
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10))
                )
                //统计单词个数
                .count()
                //转化为KStream
                .toStream()
                .map((key, value) -> {
                    String s = key.toString().split("@")[0].substring(1);
                    System.out.println("Key: " + s + ",value: " + value);
                    return new KeyValue<>(key.toString(), value.toString());
                }).to("itcast-topic-out");

        return stream;

    }
}